import { Alert, Button, Empty, Select, Tag, theme } from "antd";
import { useRequest } from "ahooks";
import { evaluationV1ControllerIndex } from "@/services/auto/evaluation";
import { Fragment, ReactNode, useEffect, useMemo, useRef } from "react";
import { EvaluationCategory } from "common/utils/data";
import Highlighter from "react-highlight-words";
import Image from "@/components/Image";
import { completeImgUrl } from "common/utils/utils";
import NoImage from "@/components/NoImage";
import { Link } from "@umijs/max";

export default function EvaluationSelect<WithDataGroup extends boolean>({
  value,
  onChange,
  category,
  withDataGroup,
  extraButtons,
  className,
}: {
  value?: Value<WithDataGroup>;
  onChange?: (val?: Value<WithDataGroup>, evaluation?: API.EvaluationIndexResult) => void;
  category: EvaluationCategory,
  withDataGroup?: WithDataGroup;
  extraButtons?: ReactNode[];
  className?: string;
}) {
  const { token } = theme.useToken();

  const { data, loading, runAsync } = useRequest((param: Partial<API.EvaluationIndexDto>) => {
    return evaluationV1ControllerIndex({ ...param, category, orderBy: 'updateTime', direction: 'DESC' })
  }, {
    manual: true,
    debounceWait: 300,
  });

  const searchValueRef = useRef<string>();

  const valueEvaluationUuid = withDataGroup ? (value as Value<true>)?.evaluationUuid : value as string;

  const currentEvaluation = data?.list.find(item => item.uuid === valueEvaluationUuid);

  useEffect(() => {
    if (valueEvaluationUuid) {
      if (!searchValueRef.current) {
        runAsync({
          uuids: valueEvaluationUuid,
        })
      }
    } else {
      runAsync({
      })
    }
  }, [valueEvaluationUuid]);

  const getDataGroupListByEvaluationUuid = (evaluationUuid?: string) => {
    return data?.list?.find(item => item.uuid === evaluationUuid)?.dataGroups
  }

  const dataGroupList = useMemo(() => {
    return getDataGroupListByEvaluationUuid(valueEvaluationUuid);
  }, [valueEvaluationUuid])


  return <div className={className}>
    <div className="flex gap-[8px]">
      <Select
        notFoundContent={
          <Empty description={<span>暂无数据 可联系送测，Q群：928537203</span>} />
        }
        className="flex-1 min-w-0"
        allowClear
        onChange={(value) => {
          onChange?.(withDataGroup ? {
            evaluationUuid: value,
            dataGroup: value ? getDataGroupListByEvaluationUuid(value)?.[0] : undefined,
          } : value as any, data?.list.find(item => item.uuid === value))
        }}
        value={valueEvaluationUuid}
        placeholder="请输入数据、品牌关键字进行搜索，最多展示匹配的20条"
        loading={loading}
        showSearch
        filterOption={false}
        onSearch={(val) => {
          searchValueRef.current = val;
          runAsync({
            keyword: val,
          })
        }}
        options={data?.list.map(item => {
          return {
            label: <Fragment>
              <Tag color="volcano" bordered={false}>{item.brand.title}</Tag>
              <Highlighter
                highlightStyle={{
                  color: token.colorError,
                }}
                highlightTag="span"
                searchWords={[searchValueRef.current!]}
                textToHighlight={item.title}
              />
            </Fragment>,
            value: item.uuid,
          }
        })}
      />
      {withDataGroup && <Select
        style={{ width: 160 }}
        value={(value as Value<true>)?.dataGroup} onChange={(val) => {
          onChange?.({
            evaluationUuid: (value as Value<true>)?.evaluationUuid,
            dataGroup: val,
          } as any)
        }} options={dataGroupList?.map(item => {
          return {
            label: item,
            value: item,
          }
        })} placeholder="请选择数据组别" />}
    </div>
    {
      currentEvaluation && <div className="flex mt-[8px] gap-[8px]">
        <div className="flex-1 min-w-0">
          {currentEvaluation.article.thumbnails?.[0] ?
            <Image
              src={completeImgUrl(currentEvaluation.article.thumbnails[0], '?x-oss-process=image/resize,m_fill,w_484,h_242')}
              style={{ width: '100%', aspectRatio: '2/1', }}
            /> :
            <NoImage
              style={{ width: '100%', aspectRatio: '2/1', }}
            />}
        </div>
        <div style={{ width: 160 }} className="flex flex-col gap-[8px]">
          <Link className="block" to={{
            pathname: `/evaluation/${currentEvaluation.uuid}`
          }} target="_blank">
            <Button block type="primary" ghost>实测数据</Button>
          </Link>
          {currentEvaluation.buyUrl && <Button
            block
            type="primary" ghost
            href={currentEvaluation.buyUrl}
            target="_blank"
          >电商详情</Button>}
          {extraButtons}
        </div>
      </div>
    }

  </div>
}

EvaluationSelect.getValidator = <WithDataGroup extends boolean,>(value: Value<WithDataGroup>, required: boolean, withDataGroup: WithDataGroup) => {
  if (withDataGroup) {
    const val = value as Value<true>
    if (val?.evaluationUuid && !val?.dataGroup) {
      return Promise.reject('请选择数据组别');
    }
    if (required && !val?.evaluationUuid) {
      return Promise.reject('请选择数据')
    }
  }
  if (required && !(value as Value<false>)) {
    return Promise.reject('请选择数据')
  }
  return Promise.resolve();
}

export type Value<WithDataGroup extends boolean> = WithDataGroup extends true ? { evaluationUuid?: string; dataGroup?: string } : string;
